package com.example.zhihu.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.example.zhihu.entity.HotDataWeek;
import com.example.zhihu.entity.HotDataWeek.DataDTO;
import com.example.zhihu.entity.HotDataWeek.DataDTO.QuestionDTO;
import com.example.zhihu.entity.HotDataWeek.DataDTO.QuestionDTO.TopicsDTO;
import com.example.zhihu.entity.HotDataWeek.DataDTO.ReactionDTO;
import com.example.zhihu.entity.WeekHot;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author t-zhaoheng
 * @since 2022/5/5
 */
@Service
public class HotDataWeekService {

  /**
   * 分页爬取周榜
   * @param limit
   * @param offset
   * @return
   */
  public List<DataDTO> getWeekHot(int limit, int offset) {
    String body = HttpRequest.get(
        "https://www.zhihu.com/api/v4/creators/rank/hot?domain=0&period=hour&offset=" + offset
            + "&limit=" + limit)
        .execute()
        .body();
    HotDataWeek hotDataWeek = JSONObject.parseObject(body, HotDataWeek.class);
    return hotDataWeek.getData();
  }

  /**
   * 将知乎数据转化为数据库对象
   * @param dataDTO
   * @return
   */
  public WeekHot convert2WeekHot(HotDataWeek.DataDTO dataDTO) {
    WeekHot weekHot = new WeekHot();
    QuestionDTO question = dataDTO.getQuestion();
    ReactionDTO reaction = dataDTO.getReaction();
    BeanUtils.copyProperties(question, weekHot);
    BeanUtils.copyProperties(reaction, weekHot);
    weekHot.setCreated(LocalDateTimeUtil.of(question.getCreated() * 1000L));
    weekHot.setUpdatedTime(LocalDateTimeUtil.of(question.getUpdatedTime() * 1000L));
    weekHot.setInsertTime(LocalDateTime.now());
    List<String> collect = question.getTopics().stream().map(TopicsDTO::getName)
        .collect(Collectors.toList());
    weekHot.setTopics(StrUtil.join(",", collect));
    return weekHot;
  }
}
